<?php
/**
 +----------------------------------------------------------
 * 发票过数AX列表
 *
 +----------------------------------------------------------
 */
class invoice_ctl_admin_axorder extends desktop_controller{

    function index(){
        
    	$this->title = '发票过数AX列表';
        $actions = array();
        $actions[] = array(
            'label' => '导入',
            'href' => 'index.php?app=omecsv&ctl=admin_import&act=progress_import&import_app=invoice&import_ctl=admin_axorder&import_act=ajax_import_axorder&import_tmpl_name=导入&import_tmpl_act=exportTemplate',
            'target' => 'dialog::{width:600,height:300,title:\'导入\'}"',
        );
        $actions[] = array(
            'label' => '导出模板',
            'href' => 'index.php?app=invoice&ctl=admin_axorder&act=exportTemplate',
            'target' => '_blank',
        );
        if(in_array($_GET['view'],array('1','3'))){
            $actions[] = array('label'=>'批量同步','submit'=>'index.php?app=invoice&ctl=admin_axorder&act=sync_bill','target'=>"dialog::{width:690,height:200,title:'批量同步'}");
        }
        
        $params = array(
            'title'=>$this->title,
            'actions' => $actions,
           
            'use_buildin_filter'=>true,
            'use_buildin_export'=>false,
            'use_buildin_import'=>false,
            'use_buildin_recycle'=>false,
            'base_filter' => $base_filter,
        );
        $this->finder('invoice_mdl_axorder', $params);
    }

   
    function _views(){
        $axorderObj = app::get('invoice')->model('axorder');
        $base_filter = array();
        $sub_menu = array(
            0 => array('label'=>app::get('base')->_('全部'),'optional'=>false),
            1 => array('label'=>app::get('base')->_('未同步'),'filter'=>array('ax_sync'=>array('0')),'optional'=>false),
            2 => array('label'=>app::get('base')->_('已同步'),'filter'=>array('ax_sync'=>array('1')),'optional'=>false),
            3 => array('label'=>app::get('base')->_('失败'),'filter'=>array('ax_sync'=>array('2')),'optional'=>false),
        );
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = array_merge($v['filter'], $base_filter);
            }
            
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $axorderObj->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=invoice&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&view='.$i++;
        }

        return $sub_menu;
    }
    
    public function ajax_import_axorder(){


//0发票代码  1发票号码    2购货单位名称  3购货纳税人识别号    4购货单位地址及电话   5购货单位开户行及账号  6购方客户电话  7购方客户邮箱  8销货单位名称  9销货单位纳税识别号   10销货单位地址电话    11销货单位银行账号    12发票类型    13收款人 14审核人 15开票人 16备注  17清单标志    18合计金额    19合计税额 20   价税合计    21开票日期    22发票状态    23作废日期    24作废人 25原发票代码   26原发票号码   27机器编号    28发票下载地址url*  29业务发票请求流水号   30快递单号    31发票请求流水号 32快递公司    33收件人 34收件人电话   35收件人地址

       //$_POST['content'] = '50001800211,78556052,周月云,,,,,,重庆理文卫生用纸制造有限公司,91500118062898557H,重庆市永川区朱沱镇四望山村023-49785555,中国建设银行股份有限公司永川支行50050114360000000149,增值税电子发票,曾粤,胡容,谭立玲,订单号:19122552945345,无清单,122.38,15.92,138.3,2019年12月25日,正数,,,,,661513392941,http://fp.baiwang.com/fp/d?d=D12BD13A49B18DA135960E3484963BF4CF690814064B6244D8A0F70471A0B90F,36544604,,36544604,,,,空';
        
        $data = explode(',', $_POST['content']);

        $invoice_code = $data[0];//发票代码
        $invoice_no = $data[1];//发票号码
        $tax_company = $data[2];//购货单位名称
        $ship_tax = $data[3];//购货纳税人识别号
        $ship_addr = $data[4];//购货单位地址及电话
        $ship_bank = $data[5];//购货单位开户行及账号
        $ship_tel = $data[6];//购方客户电话
        $payee_name = $data[8];//销货单位名称
        $tax_no = $data[9];//销货单位纳税识别号
        $address = $data[10];//销货单位地址电话
        $bank = $data[11];//销货单位银行账号
        $tax_type = $data[0];
        $payee_operator = $data[15];
        $remark = $data[16];
        $flag = '';
        $amount = $data[18];
        $cost_tax = $data[19];
        $tax_amount = $data[20];
        $tax_status = $data[22];//正数开具成功
        $org_invoice_no = $data[26];

        $dateline = $data[21];
        $axinvoiceObj = app::get('invoice')->model('axorder');
        if ($tax_status == '正数'){
            $billing_type = '1';
            $remark = str_replace('订单号:','',$remark);
            $order_bn = trim($remark);

            if (!$order_bn) {
                echo json_encode(array ('error' => '订单号不可以为空')).'ok.';exit;
            }
            $orderObj = app::get('ome')->model('orders');
           
            $order_detail  = $orderObj->dump(array('order_bn'=>$order_bn),'order_id,order_bn,shop_id,total_amount,service_price');
           
            if (!$order_detail) {
                echo json_encode(array ('error' => '订单号不存在')).'ok.';exit;
            }

            $total_amount = kernel::single('eccommon_math')->number_minus(array($order_detail['total_amount'], $order_detail['service_price']));
            //判断金额与开票金额是否一致
            if(bccomp($total_amount,(float) $tax_amount,2)!=0){
                echo json_encode(array ('error' => $order_bn.'开票金额与订单总额不一致')).'ok.';exit;
            }
        }

        

        if ($tax_status == '负数'){

            $order_detail = $axinvoiceObj->dump(array('invoice_no'=>$org_invoice_no),'id,order_bn,order_id');
            if (!$order_detail){
                echo json_encode(array ('error' => $red_tax_no.'冲蓝记录不存在!')).'ok.';exit;
            } 
            $billing_type = '2';


        }
            
        if (!in_array($billing_type,array('1','2'))){
            echo json_encode(array ('error' => $invoice_no.'发票类型未定义'));exit;
        }
        $invoice_detail = $axinvoiceObj->dump(array('invoice_no'=>$invoice_no,'billing_type'=>$billing_type),'id');
        if ($invoice_detail){
            echo json_encode(array ('error' => $invoice_no.'发票记录已存在!')).'ok.';exit;
        }

        $invoice_data = array(
            'invoice_code'  =>  $invoice_code,
            'invoice_no'    =>  $invoice_no,
            'tax_company'   =>  $tax_company,
            'ship_tax'      =>  $ship_tax,
            'ship_addr'     =>  $ship_addr,
            'ship_bank'     =>  $ship_bank,
            'ship_tel'      =>  $ship_tel,
            'payee_name'    =>  $payee_name,
            'payee_operator'=>  $payee_operator,
            'tax_no'        =>  $tax_no,
            'address'       =>  $address,
            'bank'          =>  $bank,
            'tax_amount'    =>  $tax_amount,
            'cost_tax'      =>  $cost_tax,
            'amount'        =>  $amount,
            'billing_type'  =>  $billing_type,
            'red_tax_no'    =>  $red_tax_no,
            'order_bn'      =>  $order_detail['order_bn'],
            'order_id'      =>  $order_detail['order_id'],
            'shop_id'       =>  $order_detail['shop_id'],
            'dateline'      =>  $dateline,
            'serial_no'     =>  $data[29],
            'url'           =>  $data[28],
            'org_invoice_code'=>    $data[25],
            'org_invoice_no'=>  $data[26],

        );

        $rs = kernel::single('invoice_order')->create($invoice_data);
       

        echo json_encode(array ('success' => '成功')).'ok.';exit;
    }


    public function sync_bill()
    {
        if(empty($_POST['id']) && $_POST['isSelectedAll'] != '_ALL_')
        {
            echo('没有选择执行的记录!');
            exit;
        }

        $filter          = array();

        if($_POST['isSelectedAll'] != '_ALL_')
        {
            $filter['id']    = $_POST['id'];
        }else{
            
            $filter = $_POST;

           
        }
        $filter['ax_sync|noequal']    = '1';

        $axorderObj    = app::get('invoice')->model('axorder');
        $total       = $axorderObj->count($filter);
        if($total > 100)
        {
            echo('每次最多可执行100条记录!');
            exit;
        }

        $ids        = array();
        $orderlist    = $axorderObj->getList('id', $filter);

        foreach ($orderlist as $key => $val)
        {
            $ids[]    = $val['id'];
        }
        $this->pagedata['postIds'] = json_encode($ids);
        $this->pagedata['count'] = $total;

        $this->display('admin/sync_view.html');
    }

    /**
     * 
     *
     * @return void
     * @author
     **/
    public function sync_do()
    {
        $id    = intval($_POST['id']);

        $filter    = array('id' => $id, 'ax_sync|noequal' => '1');

        $axorderObj     = app::get('invoice')->model('axorder');
        $axorder        = $axorderObj->getList('*', $filter, 0, 1);
        $axorder        = $axorder[0];

        $msg    = '';
        $result = array(
                    'rsp' => 'fail',
                    'id' => $axorder['id'],
                    'obj_bn' => $axorder['order_bn'],
                );

        if(empty($axorder))
        {
            $result['err_msg']    = '没有相关记录';
            echo json_encode($result);
            exit;
        }

        // 发起请求
        $rs    = kernel::single('invoice_order')->requestBilling($id, $err_msg);
      
        if ($rs === true)
        {
            $result['rsp']    = 'succ';
        }

        echo json_encode($result);
        exit;
    }


    function exportTemplate()
    {
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=发票导入模板-".date('Ymd').".csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');

        $data[0]        = array('发票代码','发票号码','购货单位名称','购货纳税人识别号','购货单位地址及电话','购货单位开户行及账号','购方客户电话','购方客户邮箱','销货单位名称','销货单位纳税识别号','销货单位地址电话','销货单位银行账号','发票类型','收款人','审核人','开票人','备注','清单标志','合计金额','合计税额','价税合计','开票日期','发票状态','作废日期','作废人','原发票代码','原发票号码','机器编号','发票下载地址url','业务发票请求流水号','快递单号','发票请求流水号','快递公司','收件人','收件人电话','收件人地址');
       
      
     
        foreach ($data as $items)
        {
            foreach ($items as $key => $val)
            {
                $items[$key]    = kernel::single('base_charset')->utf2local($val);
            }
            
          
            echo '"'.implode('","',$items).'"'."\n";
            
        }
        
        exit;
    }

    
}
